package main

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"gohttpserver01/metrics"
	"log"
	"math/rand"
	"net/http"
	"os"
	"time"
)

type headerHandler struct{}

//接收客户端 request，并将 request 中带的 header 写入 response header
func (m *headerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	header := r.Header
	log.Println("所有header：", header)
	w.Write([]byte("所有header"))
	for k, v := range r.Header {
		w.Header().Set(k, v[0])
		fmt.Printf("%s=%s\n", k, v[0])
		w.Write([]byte("\n"))
		w.Write([]byte(k + v[0]))
	}
	log.Println("log")
}

//当访问 localhost/healthz 时，应返回 200
func healthz(w http.ResponseWriter, r *http.Request) {
	remoteAddr := r.RemoteAddr
	statusCode := "200"
	//日志输出客户端ip和请求状态码
	log.Println("clicent Addr：" + remoteAddr + ",status code：" + statusCode)
	w.Write([]byte(statusCode))
}

//读取当前系统的环境变量中的 VERSION 配置，并写入 response header
func version(w http.ResponseWriter, r *http.Request) {
	const StringVersion = "VERSION"
	version := Getenv(StringVersion)
	//fmt.Println("get os version"+version)
	w.Header().Set(StringVersion, version)
	w.Write([]byte("get os version:" + version))
	log.Println("get os version:" + version)
}

func Getenv(key string) string {
	return os.Getenv(key)
}

func randsleep(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	randInt := rand.Intn(2000)
	time.Sleep(time.Millisecond * time.Duration(randInt))
	w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))
}

func main() {
	metrics.Register()
	a := headerHandler{}

	server := http.Server{Addr: "127.0.0.1:8081", Handler: nil}
	http.Handle("/header", &a)
	http.Handle("/randsleep", http.HandlerFunc(randsleep))
	http.Handle("/metrics", promhttp.Handler())
	http.Handle("/healthz", http.HandlerFunc(healthz))
	http.Handle("/version", http.HandlerFunc(version))

	http.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Home!"))
	})
	server.ListenAndServe()
	//println("hello http")
}
